package me.leiusual.sharing.ui

import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import dagger.android.support.DaggerAppCompatActivity
import kotlinx.android.synthetic.main.activity_start.*
import me.leiusual.sharing.BuildConfig
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.setImageUrl
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/15
 */
class StartActivity : DaggerAppCompatActivity() {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: StartViewModel by viewModels { factory }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_start)

    textView.setOnClickListener {
      startMainActivity()
    }

    // 当前版本
    text_view_version.text = "v${BuildConfig.VERSION_NAME}"

    observeData()

    viewModel.adStart()
  }

  private fun observeData() {
    viewModel.startCountDown.observe(this, Observer {
      Timber.v("startCountDown = %s", it)
      it?.run {
        val seconds = TimeUnit.MILLISECONDS.toSeconds(this)
        textView.text = "${seconds}s 跳过"
      }
      if (it == 0L) {
        startMainActivity()
      }
    })

    viewModel.adStart.observe(this, HandleObserver {
      Timber.v("asStart = %s", it)
      when (it) {
        is Data.Loading -> {
        }
        is Data.Error -> {
        }
        is Data.Success -> {
          imageView.setImageUrl(it.data)
        }
      }
    })
  }

  private fun startMainActivity() {
    startActivity(MainActivity.intent(this))
    finish()
  }
}